package com.xinhe.cn.cpbox.security;


import com.alibaba.fastjson.JSON;
import com.xinhe.cn.cpbox.common.Result;
import jodd.util.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HB
 * @date 2021/03/22 14:58
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        // 设置成JSON格式的数据
        response.setContentType("text/json");
        // 把字符集设置成“UTF-8”格式
        response.setCharacterEncoding("UTF-8");

        if (token == null || StringUtil.isBlank(token)) {
            // 拒绝访问token为空，执行登录
            response.getWriter().write(JSON.toJSONString(Result.paramError().message("无权访问，请登录")));
            return false;
        }

        // 验证token
        if (!JwtUtil.verify(token)) {
            response.getWriter().write(JSON.toJSONString(Result.paramError().message("token错误或已失效，请登录")));
            return false;
        } else {
            // 只有返回true才会继续向下执行，返回false取消当前请求
            return true;
        }
    }
}
